<?php
/**
 * Created by PhpStorm.
 * User: 86151 - 姜伟
 * Date: 2022/8/31 16:53.
 */

namespace Xinyu\Gen\Core;

use Xinyu\Gen\Core\Config\CommonConfig;
use Xinyu\Gen\Core\Libs\BaseClient;
use Xinyu\Gen\Core\Libs\CommonClient;
use Xinyu\Gen\Core\Libs\CreateClient;
use Xinyu\Gen\Core\Libs\RemoveClient;
use Xinyu\Gen\Core\Libs\ServiceClient;
use Xinyu\Gen\Core\Libs\SingletonUtil;
use Xinyu\Gen\Core\Libs\TableClient;
use Illuminate\Support\Str;

class GenClient extends BaseClient
{
    use SingletonUtil;

    // 生成model
    public function createModel($params = [])
    {
        $name = $params['name'] ?? '';
        $nameParams = CommonClient::getInstance()->getNameParamsByName($name);
        $namespaceSuffix = $nameParams['namespace_suffix'] ?? '';
        $params['name'] = $nameParams['name'] ?? '';
        $params['save_path'] = $nameParams['save_path'] ?? '';
        $type = 'Model';
        $savePath = app_path("/Models/{$name}{$type}.php");
        $savePath = CommonClient::getInstance()->makeDir($savePath);
        $importBaseModel = !empty($namespaceSuffix)
            ? PHP_EOL . 'use App\Models\BaseModel;' . PHP_EOL
            : '';
        $params['extend_replaces'] = [
            'namespace_suffix' => $namespaceSuffix,
            'import_base_model' => $importBaseModel,
        ];
        return CreateClient::getInstance()->createFile($type, $params, $savePath);
    }

    // 生成validators
    public function createValidator($params = [])
    {
        $name = $params['name'] ?? '';
        $nameParams = CommonClient::getInstance()->getNameParamsByName($name);
        $namespaceSuffix = $nameParams['namespace_suffix'] ?? '';
        $params['name'] = $nameParams['name'] ?? '';
        $params['save_path'] = $nameParams['save_path'] ?? '';
        $unique = $params['unique'] ?? '';
        $except = $params['except'] ?? '';
        $snakeName = Str::snake($params['name']);
        $type = 'Validator';
        $savePath = app_path("/Validator/{$name}{$type}.php");
        $savePath = CommonClient::getInstance()->makeDir($savePath);
        $extendReplaces = TableClient::getInstance()->getTableValidatorInfo($snakeName, $unique, $except);
        $extendReplaces['snake_name'] = $snakeName;
        $extendReplaces['namespace_suffix'] = $namespaceSuffix;
        $params['extend_replaces'] = $extendReplaces;
        return CreateClient::getInstance()->createFile($type, $params, $savePath);
    }

    // 生成service
    public function createService($params = [])
    {
        $name = $params['name'] ?? '';
        $nameParams = CommonClient::getInstance()->getNameParamsByName($name);
        $namespaceSuffix = $nameParams['namespace_suffix'] ?? '';
        $params['name'] = $nameParams['name'] ?? '';
        $params['save_path'] = $nameParams['save_path'] ?? '';
        $type = 'Service';
        $module = $params['module'];
        $savePath = app_path("/Service/{$module}/{$name}{$type}.php");
        $savePath = CommonClient::getInstance()->makeDir($savePath);
        $extendReplaces = TableClient::getInstance()->getTableServiceInfo(Str::snake($params['name']));
        $columnList = $extendReplaces['column_list'];
        unset($extendReplaces['column_list']);
        $extendReplaces['camel_primary_key'] = Str::camel($extendReplaces['primary_key']);
        $extendReplaces['module_point'] = CommonConfig::MODULE_ADMIN === $module
            ? ''
            : Str::lower($module) . '.';
        $searchString = ServiceClient::getInstance()->getSearchQueryParams($params['search'], $columnList);
        $extendReplaces['search_string'] = $searchString;
        $extendReplaces['namespace_suffix'] = $namespaceSuffix;
        $params['extend_replaces'] = $extendReplaces;
        return CreateClient::getInstance()->createFile($type, $params, $savePath);
    }

    // 生成controller
    public function createController($params = [])
    {
        $name = $params['name'] ?? '';
        $nameParams = CommonClient::getInstance()->getNameParamsByName($name);
        $namespaceSuffix = $nameParams['namespace_suffix'] ?? '';
        $params['name'] = $nameParams['name'] ?? '';
        $params['save_path'] = $nameParams['save_path'] ?? '';
        $type = 'Controller';
        $module = $params['module'] ?? '';
        $savePath = app_path("/Http/Controllers/{$module}/{$name}{$type}.php");
        $savePath = CommonClient::getInstance()->makeDir($savePath);
        $importBaseController = !empty($namespaceSuffix)
            ? PHP_EOL . 'use App\Http\Controllers\Admin\BaseAdminController;'
            : '';
        $params['extend_replaces'] = [
            'namespace_suffix' => $namespaceSuffix,
            'import_base_controller' => $importBaseController,
        ];
        return CreateClient::getInstance()->createFile($type, $params, $savePath);
    }

    // 生成controller/service/model/validator脚本
    public function createAll($params = [])
    {
        if (empty($params)) {
            return [];
        }
        $name = $params['name'] ?? '';
        if (empty($name)) {
            return $this->error('name不能为空');
        }
        $resList = [];
        $resList[] = $this->createModel($params);
        $resList[] = $this->createValidator($params);
        $resList[] = $this->createService($params);
        $resList[] = $this->createController($params);
        return $resList;
    }

    // 删除生成controller/service/model/validator脚本
    public function removeAll($params = [])
    {
        if (empty($params)) {
            return [];
        }
        $name = $params['name'] ?? '';
        if (empty($name)) {
            return $this->error('name不能为空');
        }
        $nameParams = CommonClient::getInstance()->getNameParamsByName($name);
        $savePath = ltrim($nameParams['save_path'] ?? '', '/');
        $params['save_path'] = $savePath;
        $params['name'] = $savePath;
        $module = $params['module'] ?? CommonConfig::MODULE_ADMIN;
        $RemoveClient = RemoveClient::getInstance();
        $resList = [];
        $checkModule = CommonConfig::MODULE_ADMIN === $module ? CommonConfig::MODULE_WEB : CommonConfig::MODULE_ADMIN;
        $isExist = $RemoveClient->checkModuleControllerIsExist($name, $checkModule);
        if (!$isExist) {
            $resList[] = $RemoveClient->removeModel($params);
            $resList[] = $RemoveClient->removeValidator($params);
        }
        $resList[] = $RemoveClient->removeService($params);
        $resList[] = $RemoveClient->removeController($params);
        return $resList;
    }

    // 生成路由
    public function makeRoute($params)
    {
        $controller = $params['name'] ?? '';
        if (empty($controller)) {
            return $this->error('name不能为空');
        }
        $desc = $params['desc'] ?? '';
        if (empty($desc)) {
            return $this->error('desc不能为空');
        }
        $controller = Str::studly($controller);
        $prefixRoute = Str::snake($controller);
        $mbRoute = "    // {$desc}
    Route::prefix('{$prefixRoute}')->group(function () {
        Route::post('action', [{$controller}Controller::class, 'action'])->name('{$desc}--添加/编辑');
        Route::delete('remove', [{$controller}Controller::class, 'remove'])->name('{$desc}--删除');
        Route::get('list', [{$controller}Controller::class, 'getList'])->name('{$desc}--分页列表');
    });";
        return $this->success($mbRoute);
    }

    // 生成postman接口调试参数
    public function makePostman($params)
    {
        return $this->success(TableClient::getInstance()->getPostmanRequestParams($params));
    }

    // 生成apifox接口调试参数
    public function makeApifox($params)
    {
        return $this->success(TableClient::getInstance()->getApifoxRequestParams($params));
    }
}
